<!--用户管理 管理用户-->
<template>
  <div class="admin-wrap pad">
    <div class="head">
      <span>管理员管理</span>
      <el-button @click="openAddAdminDialog" type="primary" icon="el-icon-plus" title="添加管理员" circle></el-button>
    </div>
    <div class="search-con">
      <el-input
        v-model="search.text"
        clearable
        @input="handleInput"
        @keyup.enter.native="handleSearch"
        placeholder="用户名称"
      >
        <el-select style="width: 120px;" slot="prepend" v-model="search.type">
          <el-option :value="1" label="管理员账户"></el-option>
          <el-option :value="2" label="管理员昵称"></el-option>
        </el-select>
      </el-input>
      <el-button @click="handleSearch" type="primary">搜索</el-button>
    </div>

    <el-table :data="roleList" stripe border v-loading="roleLoading" class="m-t-b">
      <el-table-column label="管理员账户" prop="userName"></el-table-column>
      <el-table-column label="管理员昵称" prop="userNickname"></el-table-column>
      <el-table-column label="角色">
        <template slot-scope="scope">
          {{scope.row.userRoleTitle || '暂无'}}
        </template>
      </el-table-column>
      <el-table-column label="关联机构名称" prop="enterpriseName"></el-table-column>
      <el-table-column label="创建时间" prop="createDate"></el-table-column>
      <el-table-column label="是否启用" fixed="right" width="160">
        <template slot-scope="scope">
          <el-switch
            active-text="启用"
            inactive-text="禁用"
            v-if="scope.row.userRoleTitle !== '超级管理员'"
            v-model="scope.row.isEnable"
            @change="changeAdminStatus($event, scope.row)"
          >
          </el-switch>
          <span v-else>禁止操作</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" fixed="right" width="150">
        <template slot-scope="scope">
          <!-- <el-button type="default" icon="el-icon-edit" circle @click="openEditDialog(scope.row)"></el-button> -->
          <el-button
            type="danger"
            icon="el-icon-refresh"
            circle
            @click="fetchResetLoginPassword(scope.row)"
            title="重置密码"
            v-if="scope.row.userRoleTitle !== '超级管理员'"
          ></el-button>
          <span v-else>禁止操作</span>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      class="flex m-t-b"
      :page-size="pageSize"
      layout="prev, pager, next"
      @current-change="handleRolePage"
      :total="roleTotal">
    </el-pagination>
    <el-dialog :title="adminDialogTitle" :visible.sync="showAdminDialog" @close="hideAdminDialog">
      <el-form :model="admin" ref="admin" :rules="rules" label-position="top">
        <el-form-item label="管理员账户" prop="userName">
          <el-input v-model="admin.userName" />
        </el-form-item>
        <el-form-item label="管理员名称" prop="userNickname">
          <el-input v-model="admin.userNickname" />
        </el-form-item>
        <el-form-item label="登录密码" prop="passwrod">
          <el-input v-model="admin.passwrod" type="password" />
        </el-form-item>
        <el-form-item label="选择角色" prop="userRoleId">
          <el-select v-model="admin.userRoleId" @change="changeRole">
            <el-option
              v-for="(item, i) in allRoleList"
              :key="i"
              :value="item.userRoleId"
              :label="item.userRoleTitle"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          label="请选择对应机构"
          v-if="roleTitle == '学校' || roleTitle == '公司'"
        >
          <el-select v-model="admin.enterpriseId" filterable>
            <el-option
              v-for="item in enterpriseList"
              :key="item.enterpriseId"
              :label="item.enterpriseName"
              :value="item.enterpriseId"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="hideAdminDialog">取 消</el-button>
        <el-button type="primary" @click="fetchAddAdmin('admin')" :loading="isDoing">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import {
  addAdminUserV2,
  getAdminUserListByPageV2,
  changeAdminUserStatusV2,
  resetLoginPassword,
  getAllRoleList
} from '../api';
import { formatDate } from '../util';
import { getAllOrganization } from '../api/version2';
import NProgress from 'nprogress';
import 'nprogress/nprogress.css';

export default {
  name: 'ClientUser',
  data () {
    const validatePassword = (rules, value, callback) => {
      let len = value.length;
      if (len < 6 || len > 15) {
        callback(new Error('密码长度在6 ~ 15个字符之间'))
      } else if (!isNaN(value)) {
        callback(new Error('密码不能为纯数字'))
      } else {
        callback()
      }
    };
    const validateAccount = (rules, value, callback) => { // 校验账户
      if (!value) {
        return callback(new Error('管理员账户不能为空'))
      };
      if (value.length < 4 || value.length > 15) {
        return callback(new Error('管理员账户在4 ~ 15个字符之间'))
      };
      if (value.indexOf('admin') !== -1) {
        return callback(new Error('管理员账户不得包含admin字样'))
      };
      callback()
    };
    const validateUserName = (rules, value, callback) => { // 校验用户名
      if (!value) {
        return callback(new Error('管理员昵称不能为空'))
      };
      if (value.length < 4 || value.length > 15) {
        return callback(new Error('管理员昵称在4 ~ 15个字符之间'))
      };
      if (value.indexOf('admin') !== -1) {
        return callback(new Error('管理员昵称不得包含admin字样'))
      };
      callback()
    };
    return {
      admin: {
        userName: '',
        userNickname: '',
        passwrod: '',
        userRoleId: '',
        enterpriseId: ''
      },
      search: {
        type: 1,
        text: ''
      },
      roleTitle: '',
      isDoing: false,
      enterpriseList: [],
      allEnterpriseList: [],
      showAdminDialog: false,
      adminDialogTitle: '添加管理员',
      allRoleList: [],
      roleList: [],
      roleTotal: 0,
      pageSize: 10,
      roleLoading: false,
      rules: {
        userName: [
          { required: true, validator: validateAccount, trigger: 'blur' }
        ],
        userNickname: [
          { required: true, validator: validateUserName, trigger: 'blur' }
        ],
        passwrod: [
          { required: true, validator: validatePassword, trigger: 'blur' }
        ],
        userRoleId: [
          { required: true, message: '请选择对应角色', trigger: 'change' }
        ]
      }
    }
  },
  methods: {
    openAddAdminDialog () { // 打开添加管理员弹出框
    if (!this.$checkAuth('addAdministrator')) {
        return this.$message.error('暂无对应操作权限!')
      };
      this.admin.userName = '';
      this.admin.userNickname = '';
      this.admin.passwrod = '';
      this.admin.userRoleId = '';
      this.adminDialogTitle = '添加管理员';
      this.showAdminDialog = true;
      this.isDoing = false;
    },
    fetchAllRole () { // 获取所有角色
      getAllRoleList()
      .then(res => {
        if (res.data.code === 1) {
          this.allRoleList = res.data.data || []
        } else {
          this.$message.error(res.data.msg || '服务异常!')
        }
      })
      .catch(e => {
        this.$message.error('服务异常!')
      })
    },
    hideAdminDialog () { // 隐藏管理员弹出框
      this.showAdminDialog = false;
      this.$nextTick(()=>{
        this.$refs['admin'].clearValidate();
      })
    },
    fetchAddAdmin (name) { // 添加管理员

      this.$refs[name].validate(valid => {
        if (valid) {
          this.isDoing = true;
          if (this.adminDialogTitle === '添加管理员') {
            addAdminUserV2({
              userName: this.admin.userName,
              userNickname: this.admin.userNickname,
              passwrod: this.admin.passwrod,
              userRoleId: this.admin.userRoleId,
              enterpriseId: this.admin.enterpriseId || null
            })
            .then(res => {
              if (res.data.code === 1) {
                this.$message({
                  type: 'success',
                  message: '添加成功'
                });
                this.showAdminDialog = false;
                this.fetchAdminUser(1)
              } else {
                this.$message.error(res.data.msg || '服务异常!')
              };
              this.isDoing = false
            })
            .catch(e => {
              this.isDoing = false;
              this.$message.error('服务异常!')
            })
          } else {
            console.log('修改')
          }
        } else {
          return false
        }
      })
    },
    fetchAdminUser (index, username, userNickname) { // 按条件查询管理员
      this.roleLoading = true;
      username = username || null;
      userNickname = userNickname || null;
      getAdminUserListByPageV2({
        index,
        count: this.pageSize,
        queryParam: {
          userName: username,
          userNickname
        }
      })
      .then(res => {
        if (res.data.code === 1) {
          let list = res.data.data.list || [];
          this.roleTotal = res.data.data.totalRecord;
          list.forEach(item => {
            item.createDate = formatDate(item.createDate, 'ZH');
            item.isEnable = item.enable ? true : false
          });
          this.roleList = list;
          console.log(this.roleList)
        } else {
          this.$message.error(res.data.msg || '服务异常!')
        };
        this.roleLoading = false
      })
      .catch(e => {
        this.roleLoading = false;
        this.$message.error('服务异常!')
      })
    },
    fetchAllOrganization () { // 查询所有机构
      getAllOrganization()
      .then(res => {
        let list = res.data.data || [];
        this.allEnterpriseList = list
      })
      .catch(e => {

      })
    },
    changeRole (e) { // 改变角色
      console.log(e);
      let curRole = this.allRoleList.find(item => item.userRoleId == e);
      if (curRole) {
        this.roleTitle = curRole.userRoleTitle
        if (this.roleTitle == '学校') {
          this.enterpriseList = this.allEnterpriseList.filter(item => item.type == 1)
        } else if (this.roleTitle == '公司') {
          this.enterpriseList = this.allEnterpriseList.filter(item => item.type == 2)
        }
      }
      console.log(curRole)
    },
    openEditDialog (data) { // 打开管理员编辑弹出框
      console.log(data)
    },
    fetchResetLoginPassword (data) { // 删除管理员
      if (!this.$checkAuth('resetPassword')) {
        return this.$message.error('暂无对应操作权限!')
      };
      this.$confirm(`确定将管理员: ${data.userNickname} 的登录密码重置吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
      .then(res => {
        resetLoginPassword(data.userId)
        .then(res => {
          if (res.data.code === 1) {
            this.$message({
              type: 'success',
              message: '重置成功!'
            })
          } else {
            this.$message.error(res.data.msg || '服务异常!')
          }
        })
        .catch(e => {
          this.$message.error('服务异常!')
        })
      })
      .catch(e => {
        this.$message({
          type: 'info',
          message: '取消操作'
        })
      })
    },
    changeAdminStatus (e, data) {
       if (!this.$checkAuth('Enabling')) {
        return this.$message.error('暂无对应操作权限!')
      };
      this.$confirm(`确定${e ? '启用' : '禁用'}此管理员?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
      .then(res => {
        changeAdminUserStatusV2(data.userId, Number(e))
        .then(res => {
          if (res.data.code === 1) {
            this.$message({
              type: 'success',
              message: '操作成功!'
            });
            this.fetchAdminUser(1)
          } else {
            this.$message.error(res.data.msg || '服务异常!')
          }
        })
        .catch(e => {
          this.$message.error('服务异常!')
        })
      })
      .catch(err => {
        data.isEnable = !e;
        this.$message({
          type: 'info',
          message: '取消操作'
        })
      })
    },
    handleRolePage (page) { //分页点击事件
      if (this.search.text.trim()) {
        if (this.search.type === 1) {
          this.fetchAdminUser(page, this.search.text, null)
        } else if (this.search.type === 2) {
          this.fetchAdminUser(page, null, this.search.text)
        }
      } else {
        this.fetchAdminUser(page)
      }
    },
    handleSearch () { // 搜索事件
     if (!this.$checkAuth('searchByUserName')) {
        return this.$message.error('暂无对应操作权限!')
      };
      if (!this.search.text.trim()) {
        return this.$message.error('搜索内容不能为空!')
      };
      if (this.search.type === 1) {
        this.fetchAdminUser(1, this.search.text, null)
      } else if (this.search.type === 2) {
        this.fetchAdminUser(1, null, this.search.text)
      }
    },
    handleInput () { // 输入框输入事件
      if (!this.search.text.trim()) {
        this.fetchAdminUser(1)
      }
    }
  },
  created () {
    this.fetchAllRole();
    this.fetchAdminUser(1);
    this.fetchAllOrganization()
  }
}
</script>
<style lang="scss">
  .admin-wrap {
    height: 100%;
    display: flex;
    flex-direction: column;
    .search-con {
      margin: 20px 0;
      display: flex;
    }
    .tab-wrap {
      flex: 1;
    }
    .pagi {
      display: flex;
      justify-content: center;
    }
  }
</style>
